import { _decorator, Component, Node, EventTouch, Vec3, ColliderComponent } from "cc";
import { CarManager } from "./CarManager";
import { MapManager } from "./MapManager";
import { AudioManager } from "./AudioManager";
import { Constants } from "../data/Constants";
import { CustomerEventListener } from "../data/CustomerEventListener";
import { UIManager } from "../ui/UIManager";
import { RunTimeData } from "../data/RunTimeData";
const { ccclass, property } = _decorator;

@ccclass("GameCtrl")
export class GameCtrl extends Component {

    @property({ type: CarManager, tooltip: '小车控制类' })
    carManager: CarManager = null;

    @property({ type: MapManager, tooltip: '地图控制类' })
    mapManager: MapManager = null;

    @property({ type: Node, })
    group: Node = null;

    onLoad(): void {
        this.resetMap();

        const collider = this.group.getComponent(ColliderComponent);
        collider.setGroup(Constants.CarGroup.NORMAL);
        collider.setMask(-1);
    }

    start(): void {

        console.log('GameCtrl start');

        UIManager.showDialog(Constants.UIPage.mainUI);

        this.node.on(Node.EventType.TOUCH_START, this.touchStart, this);
        this.node.on(Node.EventType.TOUCH_END, this.touchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.touchEnd, this);

        // 监听事件, 根据事件监听相关事件
        CustomerEventListener.on(Constants.EventName.GAME_START, this.gameStart, this);
        CustomerEventListener.on(Constants.EventName.GAME_OVER, this.gameOver, this);
        CustomerEventListener.on(Constants.EventName.NEW_LEVEL, this.newLevel, this);

        // AudioManager.playMusic(Constants.AudioSource.BACKGROUND);
    }

    private touchStart(touch: Touch, event: EventTouch): void {
        this.carManager.controlMoving(true);
    }

    private touchEnd(touch: Touch, event: EventTouch): void {
        this.carManager.controlMoving(false);
    }

    private gameStart(): void {
        UIManager.hideAll();
        UIManager.showDialog(Constants.UIPage.gameUI);
    }

    private gameOver(): void {
        UIManager.hideAll();
        UIManager.showDialog(Constants.UIPage.resultUI);
    }

    private newLevel(): void {
        UIManager.hideAll();
        UIManager.showDialog(Constants.UIPage.mainUI);
    }

    private resetMap(): void {
        this.mapManager.resetMap();
        this.carManager.reset(this.mapManager.currPath);
        RunTimeData.getInstance().maxProcess = this.mapManager.maxProcess;
    }

}